﻿using BasicInformation.ApiWrite.Application.Command.Unit;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Unit
{
    public class DelUnitHandler : IRequestHandler<DelUnitCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<DelUnitHandler> logger;

        public DelUnitHandler(DatabaseContext db,ILogger<DelUnitHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(DelUnitCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            var unit = db.SqlSugar.Queryable<UnitModel>().Where(x => x.UnitId == request.UnitId).First();
            unit.IsDel = true;
            int r = await db.SqlSugar.Updateable(unit).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "单位管理添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "单位管理添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
